package com.crazymaker.springcloud.cloud.center.zuul.config;

import com.crazymaker.springcloud.common.constants.AuthConstants;
import com.crazymaker.springcloud.standard.security.handler.JwtRefreshSuccessHandler;
import com.crazymaker.springcloud.standard.security.provider.JwtAuthenticationProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@ConditionalOnWebApplication
@EnableWebSecurity()
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.csrf().disable()
                .authorizeRequests().anyRequest().permitAll()
//                .antMatchers(
//                        "/actuator/hystrix",
//                        "/actuator/hystrix.stream",
//                        "/api/mock/**",
//                        "/v2/api-docs",
//                        "/swagger-resources/configuration/ui",
//                        "/swagger-resources",
//                        "/swagger-resources/configuration/security",
//                        "/swagger-ui.html")
//                .permitAll()
//                .antMatchers("/image/**").permitAll()
//                .antMatchers("/admin/**").hasAnyRole("ADMIN")
//                .and()
//                .authorizeRequests().anyRequest().authenticated()

                .and()

                .formLogin().disable()
                .sessionManagement().disable()
                .cors()
                .and()
//                .headers().addHeaderWriter(new StaticHeadersWriter(Arrays.asList(
//                new Header("Access-control-Allow-Origin", "*"),
//                new Header("Access-Control-Expose-Headers", AuthConstants.AUTHORIZATION))))
//                .and()
//                .addFilterAfter(new OptionsRequestFilter(), CorsFilter.class)
//                .apply(new JwtLoginConfigurer<>()).tokenValidSuccessHandler(jwtRefreshSuccessHandler()).permissiveRequestUrls("/logout")
//                .and()
                .logout().disable()
//                .addFilterBefore(new RedisSessionFilter(), SessionManagementFilter.class)
                .sessionManagement().disable();
//    		.sessionManagement().maximumSessions(1)
//                  .maxSessionsPreventsLogin(false)
//                  .expiredUrl("/login?expired")
//			      .sessionRegistry(sessionRegistry());


    }


    @Override
    public void configure(WebSecurity web) throws Exception
    {

        web.ignoring().antMatchers(
                "/actuator/hystrix.stream",
                "/actuator/hystrix",
                "/api/mock/**",
                "/v2/api-docs",
                "/swagger-resources/configuration/ui",
                "/swagger-resources",
                "/swagger-resources/configuration/security",
                "/api/crazymaker/duty/info/user/login",
                "/swagger-ui.html",
                "/css/**",
                "/js/**",
                "/images/**",
                "/webjars/**",
                "**/favicon.ico"
        );
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.authenticationProvider(daoAuthenticationProvider()).authenticationProvider(jwtAuthenticationProvider());
    }

    @Bean("jwtAuthenticationProvider" )
    protected AuthenticationProvider jwtAuthenticationProvider()
    {
        return new JwtAuthenticationProvider();
    }


    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception
    {
        return super.authenticationManagerBean();
    }


    @Bean("daoAuthenticationProvider" )
    protected AuthenticationProvider daoAuthenticationProvider() throws Exception
    {
        //这里会默认使用BCryptPasswordEncoder比对加密后的密码，注意要跟createUser时保持一致
        DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider();
        daoProvider.setUserDetailsService(userDetailsService());
        return daoProvider;
    }


    @Bean
    protected JwtRefreshSuccessHandler jwtRefreshSuccessHandler()
    {
        return new JwtRefreshSuccessHandler();
    }


    @Bean
    protected CorsConfigurationSource corsConfigurationSource()
    {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*" ));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "HEAD", "OPTION" ));
        configuration.setAllowedHeaders(Arrays.asList("*" ));
        configuration.addExposedHeader(AuthConstants.AUTHORIZATION);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}
